package com.wm.walmart.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wm.walmart.entity.User;
import com.wm.walmart.service.IUserService;
import com.wm.walmart.util.JwtToken;
import com.wm.walmart.util.Token;

@RestController
@RequestMapping("/login/")

public class LoginController {

	@Resource
	private IUserService userService;

	private Map<String, Object> map = new HashMap<String, Object>();// 将数据存入到map集合中
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@RequestMapping("logins")
	public Map<String, Object> logins(String uName, String uPword, HttpSession session) {
		User user_1 = userService.getUserByUName(uName);
		if (user_1 != null) {
			System.out.println(uPword);
			User user = userService.getUserByNameAndPas(uName, uPword);
			if (uPword.equals(user_1.getUPword())) {
				if (user_1.getIsLock().equals("否")) {
					if (user != null) {
						try {
							// 生成tokenId,有效时间时30分钟
							String tokenId = JwtToken.sign(new Token(user.getUId(), uName, uPword), 8 * 60 * 60 * 1000);
							int userId = user.getUId();
							userService.updateLastLoginTime(user_1.getUId(), sdf.format(new Date()));
							userService.updatePwdWrong(uName, 0);
							map.put("success", true);
							map.put("tokenId", tokenId);
							map.put("sendId", userId);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else {
					map.put("success", 5);
				}
			} else {
				userService.updateUserPasWrongByLoginName(uName, user_1.getExc1() + 1);// 密码错误次数
				if (user_1.getExc1() >= 3) {
					userService.updateLockOutById(user_1.getUId(), sdf.format(new Date()));// 将该用户锁定
					map.put("success", 6);
				} else {
					map.put("success", 2);
					map.put("message",
							"密码错误" + (user_1.getExc1() + 1) + "次,您还剩" + (3 - (user_1.getExc1() + 1)) + "次机会");
				}
			}
		} else {
			map.put("success", 3);
		}

		return map;
	}
}
